package scct.yanzhengxin.dao;

import com.sun.source.tree.CatchTree;
import scct.yanzhengxin.model.GoodsType;
import scct.yanzhengxin.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TypeDao {
    public List<GoodsType> getAllTypes(){
        List<GoodsType>list=new ArrayList<>();
        Connection conn= DBUtils.getConnection();
        String sql="select * from sm_goodstype";
        PreparedStatement pstmt=null;
        try {

            pstmt=conn.prepareStatement(sql);
            ResultSet rs=pstmt.executeQuery();
            while (rs.next()){
                int id= rs.getInt("id");
                String name= rs.getString("name");
                String remark= rs.getString("remark");
                list.add(new GoodsType(id,name,remark));
            }
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;

    }
    public  boolean addType(String name,String remark){
        int result=0;
        Connection conn=DBUtils.getConnection();
        String sql="insert into sm_goodstype values(null,?,?)";
        try {
            PreparedStatement pstmt= conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2,remark);
            result= pstmt.executeUpdate();
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return  result>0;

    }

    public boolean updateType(int id,String name,String remark) {
        int result=0;
        Connection conn=DBUtils.getConnection();
        String sql="update sm_goodstype set name=?,remark=? where id=?";

        try {
            PreparedStatement pstmt= conn.prepareStatement(sql);
            pstmt= conn.prepareStatement(sql);
            pstmt.setString(1,name);
            pstmt.setString(2,remark);
            result= pstmt.executeUpdate();
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return  result>0;


    }
}
